/////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009 Eric Bowen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
// associated documentation files (the "Software"), to deal in the Software without restriction, including 
// without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
// copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the 
// following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial 
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Author's blog: http://blog.scrappydog.com
// Updated source code available:  http://scrappydb.codeplex.com
/////////////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Web.Caching;
using ScrappyDB.Attributes;

namespace ScrappyDB.BaseClasses
{
    public class SdbEntity
    {
        private IDb _db;
        private bool _dirty = true;

        private Cache _webCache;

        public SdbEntity()
        {
            CreateDate = DateTime.Now.ToUniversalTime();
        }

        public SdbEntity(Cache cache)
        {
            WebCache = cache;
            CreateDate = DateTime.Now.ToUniversalTime();
        }

        [DoNotPersist]
        public Cache WebCache
        {
            get { return _webCache; }
            set
            {
                _webCache = value;

                if (Db != null)
                    Db.WebCache = _webCache;
            }
        }

        [DoNotPersist]
        public IDb Db
        {
            get
            {
                return _db ?? (_db = new Repository(WebCache).DB());
            }
            set { _db = value; }
        }

        //public void Find(string id)
        //{
        //    var db = new DB();
        //    this = db.Find<DbEntity>(id);
        //}

        /// <summary>
        /// LastUpdated is auto populated and it is only persisted to the database if the 
        /// [AutoCreateUpdateDate] attribute is set on the entity
        /// </summary>
        public DateTime LastUpdated { get; set; }

        /// <summary>
        /// CreateDate must be set by the application (it is NOT autogenerated). It is only persisted 
        /// to the database if the [AutoCreateUpdateDate] attribute is set on the entity
        /// </summary>
        public DateTime CreateDate { get; set; }

        //TODO: We may want to implement logic to delete the previous version of a record when a user changes
        //the value of the property marked with [ItemName] attribute... (the point being to avoid creating 
        //unwanted duplicate records)

        /// <summary>
        /// This value is autogenerated by SimpleDB, and exists here as a convenience to SimpleDB processes.
        /// It should always match the unmodified (previous) value of the property marked with [ItemName] attribute.
        /// Note: This is always the ENCODED value.
        /// </summary>
        [DoNotPersist]
        public string ItemName { get; set; }

        /// <summary>
        /// Currently this is NOT automagically implemented.
        /// Dirty will always be true unless an inheriting entity implements
        /// </summary>
        [DoNotPersist]
        public bool Dirty
        {
            get { return _dirty; }
            set { _dirty = value; }
        }

        /// <summary>
        /// The intention of this is to explicitly block lazy loading of child objects.
        /// Currently this is NOT automagically implemented. It is up to the developer to implement in their own objects.
        /// </summary>
        [DoNotPersist]
        public bool IsLazyLoadEnabled { get; set; }

        public List<string> Tags { get; set; }

        public void UpdateTags()
        {
            throw new NotSupportedException(
                "This method should always be overridden (basically it's abstact, but the class isn't... yes, we've heard of interfaces... :-)");
        }

        public void Save()
        {
            InternalSave();
        }

        public void Save(Cache cache)
        {
            WebCache = cache;
            InternalSave();
        }

        private void InternalSave()
        {
            Db.SaveChanges(this);
        }
    }
}